// pages/music-detail/index.js
import {musicStore} from '../../store/index'
import {getMusicDetail} from '../../services/music-api'
const globalData = getApp().globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    currentSong:{},
    currentSwiperIndex:0,
    contentHeight:0,
    currentTime:0,
    value:0,
    isPlaying:true,
    isChanging:false,
    lyrics:[],
    currentLyricIndex:0,
    show:false,
    musicList:[],
    currentIndex:0
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {id} = options
    const contentHeight = globalData.screenHeight - globalData.statusBarHeight - 44 
    this.setData({id,contentHeight})

    musicStore.onState('lyrics',value => {
      if(value.length === 0 ) return 
      this.setData({lyrics:value})
    })
    musicStore.onState('songInfo',value => {
      if(Object.keys(value).length === 0 ) return
      this.setData({currentSong:value})
    })
    musicStore.onState('currentLyricIndex',value => {
      this.setData({currentLyricIndex:value})
    })
    musicStore.onState('currentTime',res => {
      const currentTime = res
      if(this.data.isChanging) return
      const value = res / this.data.currentSong.dt * 100
      this.setData({currentTime,value})
    })
    musicStore.onState('musicList',res => {
      getMusicDetail([...res].join(',')).then(res => {
        const musicList = res.songs
        this.setData({musicList})
      })
    })
    musicStore.onState('currentIndex',value => {
      this.setData({currentIndex:value})
    })
    musicStore.onState('isPlaying',value => {
      this.setData({isPlaying:value})
    })
    
  },
  handleSwiperChange(e){
    const currentSwiperIndex = e.detail.current
    this.setData({currentSwiperIndex})
  },
  handleSliderChange(e){
    const value = e.detail.value
    musicStore.dispatch('changeMusicCurrentTimeAction',value)
    this.setData({isChanging:false})
  },
  handleSliderChanging(e){
    const value = e.detail.value 
    const currentTime = this.data.currentSong.dt * (value / 100)
    this.setData({currentTime,isChanging:true})
  },
  changeMusicState(){
    musicStore.dispatch('changeMusicStatusAction',!this.data.isPlaying)
  },
  handleMusicPrevChange(){
    musicStore.dispatch('changeNewMusicAction',false)
  },
  handleMusicNextChange(){
    musicStore.dispatch('changeNewMusicAction')
  },
  showMusicList(){
    this.setData({show:!this.data.show})
  },
  handleClose(){
    this.setData({show:false})
  },
  playMusic(e){
    const id = e.currentTarget.dataset.id
    musicStore.dispatch('playMusicWithIdAction',id)
  }
  
})